package org.rendao.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.rendao.exception.TBFError;
import org.rendao.exception.TBFException;

public class AssembleUtils {

	public static <S, T> T shadowCopy(S sourceObject, Class<T> targetObjectType) {
		if (sourceObject == null) {
			throw new TBFException(TBFError.SHADOWCOPY_SOURCE_NULL);
		}

		T targetObject = null;
		try {
			targetObject = targetObjectType.newInstance();
			Field[] srcFields = sourceObject.getClass().getDeclaredFields();
			Field[] tgtFields = targetObjectType.getDeclaredFields();

			String srcFieldName = null;
			Class srcFieldType = null;
			String tgtFieldName = null;
			Class tgtFieldType = null;
			for (Field srcField : srcFields) {
				srcField.setAccessible(true);
				srcFieldName = srcField.getName();
				srcFieldType = srcField.getType();
				for (Field tgtField : tgtFields) {
					tgtField.setAccessible(true);
					tgtFieldName = tgtField.getName();
					tgtFieldType = tgtField.getType();
					if (srcFieldName.equals(tgtFieldName)
							&& srcFieldType.equals(tgtFieldType)) {
						Object value = srcField.get(sourceObject);
						tgtField.set(targetObject, value);
					}
				}
			}
		} catch (Exception e) {
			throw new TBFException(new TBFError(e));
		}
		return targetObject;
	}

	public static <S, T> List<T> shadowCopyList(List<S> sourceList, Class<T> targetItemType) {
		List<T> result = new ArrayList<T>();
		for (S s : sourceList) {
			T t = (T) shadowCopy(s, targetItemType);
			result.add(t);
		}
		return result;
	}
}
